//
//  ViewController.m
//  3.6、UITableView控件数据刷新
//
//  Created by 李坤 on 16/12/7.
//
//

#import "ViewController.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
//数据
@property(nonatomic,copy)NSMutableArray<NSString *> *data;
//tableview
@property(nonatomic,weak)UITableView *tableview;
@end

@implementation ViewController

- (NSMutableArray<NSString *> *)data{
    if(!_data){
        _data = [NSMutableArray array];
        for (int i = 0; i<100; i++) {
            [_data addObject:[NSString stringWithFormat:@"点击修改数据%i",i]];
        }
    }
    return _data;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if(!cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.textLabel.text = [self.data objectAtIndex:indexPath.row];
    return cell;
}

//选中一行时候调用的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%s",__func__);
    UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"修改数据" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    av.alertViewStyle = UIAlertViewStylePlainTextInput;
    UITextField *text = [av textFieldAtIndex:0];
    text.text = self.data[indexPath.row];
    av.tag = indexPath.row;
    [av show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    UITextField *text = [alertView textFieldAtIndex:0];
    NSString *str = text.text;
    [self.data replaceObjectAtIndex:alertView.tag withObject:str];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:alertView.tag inSection:0];
    [self.tableview reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
    //下面代码为删除行的代码
    /**
    [self.data removeObjectAtIndex:indexPath.row];
    [self.tableview deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
     **/
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UITableView *tv = [[UITableView alloc] init];
    tv.dataSource = self;
    tv.delegate = self;
    tv.frame = self.view.bounds;
    [self.view addSubview:tv];
    self.tableview = tv;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
